package org.example;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.Transaction;
import redis.clients.jedis.exceptions.JedisDataException;
import redis.clients.jedis.exceptions.JedisException;

public class service {
    private String userid;
    private int quantity;

    public service(String userid, int quantity) {
        this.userid = userid;
        this.quantity = quantity;
    }

    public void purchase() {
        Jedis jedis = new Jedis("localhost",6379);
        String key = "stock:product1";

        try {
            jedis.watch(key);
            String value = jedis.get(key);
            if (value == null) {
                System.out.println("商品不存在");
                return;
            }
            long current = Long.parseLong(value);
            if (current < quantity) {
                System.out.println("用户"+userid+"商品不足");
                return;
            }
            Transaction transaction = jedis.multi();
            transaction.decrBy(key, quantity);
            transaction.exec();
            System.out.println("用户"+userid+"购买成功了"+quantity+"件商品");
        }catch (JedisDataException e) {
            e.printStackTrace();
        }
        finally {
            jedis.close();
        }
    }
}
